<template>
  <div class="memeory-bg write-bg">
    <Header :isTransBg="true" :width="1000" :isGoBack="false">
      <template v-slot:left>
        <span class="weight-title">
          {{ checkedBookData.edition_name }}-{{ checkedBookData.grade_name }}
        </span>
      </template>
      <template v-slot:right>
        <div class="close-memeory" @click="goStudyCenter">
          关闭
          <img class="ml5" src="@/assets/img/close-circle.png" alt="" />
        </div>
      </template>
    </Header>
    <div class="memory-container w1000">
      <div class="memory-contain">
        <div class="memory-question">
          <div>
            <div class="memory-header">
              <span class="title">智能默写</span>
              <span class="fr reminder-text">
                按"Enter"进入下一题
                <span class="feedback-btn ml10 click" @click="showFeedBack">
                  反馈
                </span>
              </span>
            </div>
            <StudyQuestion
              v-if="intensiveWord.word_id"
              :wordData="intensiveWord"
              @nextWord="nextIntensiveWord"
              @checkTrueFun="checkTrueFun"
              ref="studyQuestion"
              :type="1"
              :category="3"
              :isOpenMessageBox="isOpenMessageBox"
            ></StudyQuestion>
          </div>
        </div>

        <div v-if="intensiveWord.word_id && !isReview">
          <span> </span>
          <span> 本次学习：生词：{{ newWordNum }} 熟词：{{ skilledNum }} </span>
        </div>
        <div v-if="isReview">
          <span> </span>
          <span>
            进度 {{ intensiveWordIndex + 1 }}/{{ intensiveWordList.length }}
          </span>
        </div>
      </div>
    </div>
    <Feedback ref="feedback" :type="1" :classify="1"></Feedback>
  </div>
</template>
<script>
import Header from "@/components/Header";
import StudyQuestion from "../components/StudyQuestion";
import Feedback from "@/components/Feedback";
import EventBus from "@/assets/js/eventBus";
// import { throttle } from "../../../utils/utils";
import {
  getStudyWordList,
  setWordExercise,
  getMemoryReview,
  setWordPass,
  addIntegral,
  getReviewNumber,
} from "@/api/index";
export default {
  data() {
    return {
      intensiveWordList: [],
      intensiveWordIndex: -1,
      intensiveWord: {},
      groupData: {},

      checkedBookData: null,
      unitId: null,
      newWordNum: 0,
      skilledNum: 0,
      reviewNum: 0,
      category: 3,
      addIntegralNum: 0,
      isOpenMessageBox: false,
    };
  },
  methods: {
    showFeedBack() {
      if (this.intensiveWord.word_id) {
        this.$refs.feedback.visible(this.intensiveWord.word_id);
      }
    },
    addIntegral(groupId) {
      let params = {
        groupId,
        source: this.category,
        bookId: this.checkedBookData.book_id,
        unitId: this.unitId,
        type: 1,
      };
      addIntegral(params).then((res) => {
        if (res.code == 200) {
          this.addIntegralNum += res.data;
        }
      });
    },
    nextIntensiveWord: function () {
      console.log(this.intensiveWord);
      if (this.intensiveWordList.length <= 0) {
        return;
      }
      if (
        this.intensiveWordIndex < this.intensiveWordList.length - 1 &&
        this.intensiveWordList.length > 0
      ) {
        this.intensiveWordIndex++;
        this.setIntensiveWordData(
          this.intensiveWordList[this.intensiveWordIndex]
        );
      } else {
        this.getStudyData();
      }
    },
    setIntensiveWordData(data) {
      this.intensiveWord = data;
      this.intensiveWord.startTime = new Date().getTime();
    },
    setWordPass(data) {
      if (data) {
        let num = this.intensiveWord.wrongNum;
        console.log(num);
        let data = {
          category: this.category,
          book_id: this.checkedBookData.book_id,
          word_id: this.intensiveWord.word_id,
          memory_strength: 30 - num * 10 < 0 ? 0 : 30 - num * 10,
        };
        setWordPass(data);
      }
    },
    setWordExercise(not) {
      let data = {
        groupId: this.groupData.group_id,
        wid: this.intensiveWord.wid,
        wordId: this.intensiveWord.word_id,
        not: not,
        bookId: this.checkedBookData.book_id,
        number: this.checkedBookData.number,
        unitId: this.unitId,
        useTime: parseInt(
          (this.intensiveWord.endTime - this.intensiveWord.startTime) / 1000
        ),
        source: this.category,
      };
      setWordExercise(data);
    },

    checkTrueFun(not) {
      // 词义强化答对
      this.intensiveWord.endTime = new Date().getTime();
      if (this.isReview) {
        this.setWordPass(not);
      } else {
        this.setWordExercise(not);
      }
      if (not) {
        if (this.intensiveWord.wrongNum > 0) {
          //答错的插2个之后
          if (this.intensiveWordIndex + 3 < this.intensiveWordList.length) {
            this.intensiveWordList.splice(
              this.intensiveWordIndex + 3,
              0,
              Object.assign({}, this.intensiveWord, {
                isReview: true,
                wrongNum: 0,
              })
            );
          } else {
            this.intensiveWordList.push(
              Object.assign({}, this.intensiveWord, {
                isReview: true,
                wrongNum: 0,
              })
            );
          }
        }
        if (this.intensiveWord.isReview) {
          this.reviewNum++;
        } else {
          if (this.intensiveWord.wrongNum > 0) {
            this.newWordNum++;
          } else {
            this.skilledNum++;
          }
        }
      }
    },
    goStudyCenter() {
      this.$router.push({
        name: "studyCenter",
      });
    },
    getStudyWordList() {
      let params = {
        unitId: this.unitId,
        phoneticCategory: this.$store.getters.isBritish,
        bookId: this.checkedBookData.book_id,
        number: this.checkedBookData.number,
        source: this.category,
      };
      EventBus.$emit("openLoading", {});
      getStudyWordList(params)
        .then((res) => {
          EventBus.$emit("closeLoading", {});
          if (
            res.code == 200 &&
            res.data &&
            res.data.word_pronunciation_vo_list &&
            res.data.word_pronunciation_vo_list.length > 0
          ) {
            if (
              this.groupData &&
              this.groupData.group_id &&
              this.groupData.group_id !== res.data.group_id
            ) {
              this.addIntegral(this.groupData.group_id);
            }
            res.data.word_pronunciation_vo_list.forEach((item) => {
              let paraphrase = [];
              item.word_paraphrase_vo_list.map((item2) => {
                paraphrase.push(
                  (item2.word_sex ? item2.word_sex : "") + item2.paraphrase
                );
              });
              item.id = item.word_id; //ID
              // item.name = item.word_name; //单词
              // item.phonetic = item.phonetic_american; //音标
              // item.imgURL =
              //   item.word_picture_vo_list.length > 0
              //     ? item.word_picture_vo_list[0].url
              //     : ""; //图片
              // item.exampleList = item.word_example_vo_list; //例句
              item.audioURL = item.word_audio_vo_list[0]
                ? item.word_audio_vo_list[0].url
                : ""; //音频
              item.paraphrase = paraphrase; //释义
            });
            this.intensiveWordIndex = -1;
            this.groupData = res.data;

            this.intensiveWordList = res.data.word_pronunciation_vo_list.filter(
              (word) => {
                word.checkedNum = 0;
                word.wrongNum = 0;
                return (
                  (word.is_strange == 1 && word.correct_num < 1) ||
                  (word.is_strange == 0 && word.correct_num < 0) ||
                  (word.is_strange != 1 && word.is_strange != 0)
                );
              }
            );

            this.nextIntensiveWord();
          } else {
            if (this.groupData && this.groupData.group_id) {
              this.addIntegral(this.groupData.group_id);
            }
            if (!this.isOpenMessageBox) {
              this.isOpenMessageBox = true;
              this.$confirm("智能默写学习已完成,前往极速挑战", "提示", {
                confirmButtonText: "极速模式",
                cancelButtonText: "普通模式",
                showClose: true,
                closeOnClickModal: false,
                closeOnPressEscape: false,
                distinguishCancelAndClose: true,
                beforeClose: (action, instance, done) => {
                  this.$beforeConfirmClose(action, instance, done);
                },
              })
                .then(() => {
                  this.isOpenMessageBox = false;
                  this.$router.push({
                    name: "quickTest",
                    query: {
                      unitId: this.unitId,
                      category: this.category,
                    },
                  });
                })
                .catch((type) => {
                  this.isOpenMessageBox = false;
                  if (type != "close") {
                    this.$router.push({
                      name: "generalTest",
                      query: {
                        unitId: this.unitId,
                        category: this.category,
                      },
                    });
                  } else {
                    this.$router.push({
                      name: "studyCenter",
                    });
                  }
                });
            }
          }
        })
        .catch(() => {
          EventBus.$emit("closeLoading", {});
        });
    },
    getMemoryReview() {
      let data = {
        page_require: {
          page_num: 1,
          page_size: 10,
        },
        category: this.category,
        book_id: this.checkedBookData.book_id,
      };
      getMemoryReview(data).then((res) => {
        if (res.code == 200 && res.data) {
          res.data.word_info_list.forEach((item) => {
            item.id = item.word_id; //ID
            item.name = item.word_name; //单词
            item.imgURL = ""; //图片
            item.exampleList = []; //例句
            item.paraphrase = item.paraphrase.split("\n"); //释义
            item.phonetic =
              this.$store.getters.isBritish == 1
                ? item.phonetic_british
                : item.phonetic_american; //音标
            item.audioURL =
              this.$store.getters.isBritish == 1 ? item.en_url : item.us_url; //音频
          });
          let data = res.data.word_info_list.filter((item) => {
            item.checkedNum = 0;
            item.wrongNum = 0;
            return item.time_interval <= 0;
          });
          if (data.length > 0) {
            this.intensiveWordIndex = -1;
            this.intensiveWordList = data;
            this.nextIntensiveWord();
          } else {
            if (!this.isOpenMessageBox) {
              this.isOpenMessageBox = true;
              this.$alert("智能默写已复习完成", "消息提示", {
                confirmButtonText: "确定",
                callback: () => {
                  this.isOpenMessageBox = false;
                  this.goStudyCenter();
                },
              });
              // this.$confirm(`智能默写已复习完成`, "提示", {
              //   confirmButtonText: "返回学习中心",
              //   cancelButtonText: "取消",
              // })
              //   .then(() => {
              //     this.isOpenMessageBox = false;
              //     this.$router.push({
              //       name: "studyCenter",
              //     });
              //   })
              //   .catch(() => {
              //     this.isOpenMessageBox = false;
              //     return false;
              //   });
            }
          }
        }
      });
    },
    getStudyData() {
      if (this.isReview) {
        this.getMemoryReview();
      } else {
        this.getStudyWordList();
      }
    },
    getReviewNumber() {
      return new Promise((reslove) => {
        getReviewNumber(this.checkedBookData.book_id)
          .then((res) => {
            if (res.code == 200 && res.data) {
              console.log(res);
              let data = res.data.filter((item) => {
                return item.category > this.category && item.num > 0;
              });
              if (data.length > 0) {
                reslove(data[0]);
              }
            }
            reslove(null);
          })
          .catch(() => {
            reslove(null);
          });
      });
    },
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    let data = this.checkedBookData.word_book_vo_list.filter((item) => {
      return item.source == this.category;
    });
    if (data.length > 0) {
      this.checkedBookData.number = data[0].number;
    } else {
      this.checkedBookData.number = 1;
    }
    this.unitId = this.$route.query.unitId;
    this.isReview = !!this.$route.query.isReview;
    this.getStudyData();
  },
  beforeDestroy() {},
  components: {
    StudyQuestion,
    Header,
    Feedback,
  },
};
</script>
